from __future__ import with_statement

from crv.model import DBSession, metadata
from crv.model.crvmodel import *
from crv.tools.clustermgr import ClusterMgr
from crv.tools.rolemgr import RoleMgr
from crv.tools.vmmgr import VMMgr

import logging
log = logging.getLogger(__name__)

def checkAll2():
    while True:
        checkAll2()
        
def checkAll():
    log.debug("checkAll Called")
    log.debug("#"*256)
    clMgr=ClusterMgr.getInstance()
    rlMgr=RoleMgr.getInstance()
    vmMgr=VMMgr.getInstance()    

    vms = DBSession.query(VM).all()
    log.debug("checkAll::vms=%s"%str(vms))

    for ivm in vms:
#        DBSession.expire(ivm)
        log.debug("checking VM:%s"%ivm.name)
        #        with NamedLock("VM"):
        vmMgr.advanceStates(ivm)
        log.debug("Committing")

                
    log.debug("DIRTY=%s"%str(DBSession.dirty))
    transaction.commit()
    #raw_input("Press key to continue...")


    log.debug("*"*128)

    roles = DBSession.query(Role).all()
    log.debug("checkAll::roles=%s"%str(roles))
    for irole in roles:
#        DBSession.expire(irole)
        log.debug("checking Role:%s"%irole.name)
        #        with NamedLock("Role"):
        rlMgr.advanceStates(irole)
        log.debug("Committing")


    log.debug("DIRTY=%s"%str(DBSession.dirty))
    transaction.commit()
    #raw_input("Press key to continue...")

    log.debug("*"*128)

    clusters = DBSession.query(Cluster).all()
    log.debug("checkAll::clusters=%s"%str(clusters))
    for icluster in clusters:
#        DBSession.expire(icluster)
        log.debug("checking Cluster:%s"%icluster.name)
        #with NamedLock("Cluster"):
        clMgr.advanceStates(icluster)
        log.debug("Committing")
    
    log.debug("DIRTY=%s"%str(DBSession.dirty))
    transaction.commit()
    #raw_input("Press key to continue...")
    
def buildRoleDep(roles):
    for i in range(len(roles)):
        for j in range(i):
            if roles[j].roleDef in roles[i].roleDef.dependOn: #i depend on j
                #log.debug("buildRoleDep:"+ roles[i].name+ " depends on "+ roles[j].name)
                roles[i].dependOn.append(roles[j])

